package com.qf.base.service.impl;

import com.qf.base.domain.BaseCarrier;
import com.qf.base.domain.BaseVehicle;
import com.qf.base.mapper.BaseCarrierMapper;
import com.qf.base.mapper.BaseVehicleMapper;
import com.qf.base.service.IBaseVehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * --- ONE PIECE ---
 *
 * @author yangjiangcheng
 * @date 2025/9/3
 * @desc
 */
@Service
public class BaseVehicleServiceImpl implements IBaseVehicleService {
    @Autowired
    private BaseVehicleMapper baseVehicleMapper;

    @Autowired
    private BaseCarrierMapper baseCarrierMapper; // 注入承运商Mapper

    @Override
    public List<BaseVehicle> selectVehicleList(BaseVehicle baseVehicle) {
        return baseVehicleMapper.selectVehicleList(baseVehicle);
    }

    // 新增车辆时同步更新
    @Override
    public int insertVehicle(BaseVehicle baseVehicle) {
        int result = baseVehicleMapper.insertVehicle(baseVehicle);
        // 若车辆关联了承运商，同步更新数量
        if (baseVehicle.getCarrierId() != null) {
            syncCarrierVehicleCount(baseVehicle.getCarrierId());
        }
        return result;
    }

    @Override
    public int updateVehicle(BaseVehicle baseVehicle) {
        return baseVehicleMapper.updateVehicle(baseVehicle);
    }

    @Override
    public BaseVehicle selectVehicleById(Long vehicleId) {
        return baseVehicleMapper.selectVehicleById(vehicleId);
    }


    // 删除车辆时同步更新
    @Override
    public int deleteVehicleByIds(Long[] vehicleIds) {
        // 先查询这些车辆所属的承运商ID（去重）
        List<Long> carrierIds = baseVehicleMapper.selectCarrierIdsByVehicleIds(vehicleIds);
        int result = baseVehicleMapper.deleteVehicleByIds(vehicleIds);
        // 同步更新每个关联承运商的车辆数量
        carrierIds.forEach(this::syncCarrierVehicleCount);
        return result;
    }


    // 核心：同步指定承运商的车辆数量
    @Override
    public void syncCarrierVehicleCount(Long carrierId) {
        // 1. 查询该承运商下的车辆总数
        int vehicleCount = baseVehicleMapper.countByCarrierId(carrierId);
        // 2. 更新承运商表的vehicle_count字段
        BaseCarrier carrier = new BaseCarrier();
        carrier.setCarrierId(carrierId);
        carrier.setVehicleCount((long)vehicleCount);
        baseCarrierMapper.updateVehicleCount(carrier);
    }

}
